<script>
import Service from '@/utils/Service.js';
import Tools from '@/utils/Tools.js';
import { ChatIM } from '@/utils/IM.js';
import store from '@/store/index.js';
// #ifdef APP-PLUS
import { NativeMessageBall } from '@/entity/NativeMessageBall.class.js';
import permission from '@/js_sdk/AppPermission/permission.js';
import { saveNewVersion } from '@/store/dispatches.js';
// #endif
import { updateNetworkType, updataDeviceModel, updateDevicePermission, updateRefereeCode, initIMService, reconnctionIMService, storageCache } from '@/store/dispatches.js';

export default {
	onLaunch: function(options) {
		updataDeviceModel(uni.getSystemInfoSync().model);
		Service.updateApplication();
		console.log('App Launch');
		// #ifdef APP-PLUS
		this.globalData.$u = this.$u;
		// this.globalData.nativeMessageBall = new NativeMessageBall();
		// setTimeout(() => {
		// 	this.globalData.nativeMessageBall.setNoRead({ thumb: 'http://tfile.anyyun.cn/suisui/temp/1.jpg', number: 100 });
		// }, 5000);

		// plus.push.addEventListener(
		// 	'click',
		// 	e => {
		// 		console.log(e);
		// 	},
		// 	false
		// );
		plus.push.addEventListener(
			'receive',
			e => {
				this.handlePushNotice(e);
			},
			false
		);
		// #endif
		uni.getNetworkType({
			success: ressult => {
				updateNetworkType(ressult.networkType);
				console.log(ressult);
				uni.onNetworkStatusChange(res => {
					updateNetworkType(res.networkType);
					console.log(res);
				});
			}
		});
		// #ifndef APP-PLUS
		let refereeCode = '';
		// #ifdef H5
		refereeCode = options.query.s || '';
		// #endif
		// #ifdef MP
		refereeCode = Tools.getUrlQuery(decodeURIComponent(options.q) || '', 's') || '';
		// #endif
		if (refereeCode) {
			updateRefereeCode(options.query.s);
		}
		// #endif

		// #ifndef H5
		uni.onKeyboardHeightChange(res => {
			if (res.height > 0) {
				storageCache({ key: 'keyboardHeight', value: res.height });
			}
		});
		// #endif
		// #ifdef H5
		uni.setStorageSync('entryUrl', location.href.split('#')[0]);
		// #endif

		uni.$on('globeRefreshUserInfo', data => {
			this.refreshUserInfo();
		});

		this.$u.api.init().then(res => {
			storageCache({ key: 'vipBanner', value: res.data.vip });
			storageCache({ key: 'loginadv', value: res.data.loginadv });
			storageCache({ key: 'adv', value: res.data.adv });
			// #ifdef APP-PLUS
			const newVersion = res.data.version;
			saveNewVersion(newVersion);
			console.log();
			const { smeta } = newVersion;
			if (smeta.need_update == 1) {
				const upDater = uni.requireNativePlugin('CL-UpDater');
				let options = {
					title: !smeta.is_force ? '强制升级' : '更新',
					con: smeta.brief,
					downUrl: smeta.download,
					hidCancelbtn: !smeta.is_force,
					btnBgColor: '#F85962',
					topImgBg: plus.io.convertLocalFileSystemURL('_www/hybrid') + '/top.png'
				};
				upDater.startUpdate(options);
			}
			// #endif
		});
	},
	onShow: async function() {
		console.log('App Show');

		// #ifndef APP-PLUS
		if (store.state.user.token) {
			this.$u.api.checkToken().then(res => {
				if (res.data.token_valid == 1) {
					if (store.state.chat.IMEntity) {
						reconnctionIMService(true);
					} else {
						initIMService();
					}
				}
			});
		}
		// #endif
		// #ifdef APP-PLUS
		console.log(plus.runtime);
		const args = plus.runtime.arguments;
		if (store.state.user.token) {
			this.$u.api.checkToken().then(res => {
				if (res.data.token_valid == 1) {
					// socket处理
					if (store.state.chat.IMEntity) {
						reconnctionIMService(true);
					} else {
						initIMService();
					}
					// 企图拉起对应页面
					if (args) {
						const result = Service.analysisAppArguments(args);
						if (result.validity && result.path) {
							uni.navigateTo({
								url: result.path
							});
						}
						console.log(result);
					}
				}
			});

			plus.runtime.arguments = '';
		}
		Service.cacheShareServiceProvider();

		// this.globalData.pagesPathTimer = setInterval(() => {
		// 	const currentPages = getCurrentPages();
		// 	if (this.globalData.nativeMessageBall && currentPages.length > 0) {
		// 		this.globalData.nativeMessageBall.setAbleShow(!(this.globalData.noBallPages.indexOf('/' + currentPages[currentPages.length - 1].route) >= 0));
		// 	}
		// }, 1000);
		updateDevicePermission({ key: 'notice', value: permission.judgePermissionPush() });

		// #endif
		try {
			const locationPermission = await Service.getLocationPermission();
			updateDevicePermission({ key: 'location', value: locationPermission });
		} catch (e) {
			updateDevicePermission({ key: 'location', value: false });
		}
	},

	onHide: function() {
		console.log('App Hide');
		clearInterval(this.globalData.pagesPathTimer);
	},
	// onError: function(e) {
	// 	console.log(e.name);
	// 	setTimeout(() => {
	// 		let fullPath = null;
	// 		const pages = getCurrentPages();
	// 		if (pages.length > 0) {
	// 			fullPath = pages[pages.length - 1].$route.fullPath;
	// 		}
	// 		this.$u.api.submitErrorConsole(String(e.toString()), fullPath, e.name || null);
	// 	});
	// 	console.log(e);
	// },
	globalData: {
		tabBarLinks: ['/pages/index/index', '/pages/chat/index', '/pages/find/index', '/pages/mall/index', '/pages/mine/index'],
		noLoginPages: ['/pageUser/login/index', '/pageUser/login/bind'],

		// #ifdef APP-PLUS
		$u: {},
		noBallPages: ['/pages/index/index', '/pageChat/single/index', '/pageUser/chat/single', '/pageUser/chat/group', '/pageUser/login/bind', '/pageUser/login/code', '/pageUser/login/index', '/pageUser/login/matchmaker', 'pageUser/login/member', '/pageUser/zone/member'],
		nativeMessageBall: null,
		pagesPathTimer: null

		// #endif
	},
	methods: {
		handlePushNotice(data) {
			if (store.state.user.token) {
				this.$u.api.checkToken().then(res => {
					let { payload } = data;
					payload = JSON.parse(payload);
					if (payload.hasOwnProperty('path')) {
						this.navigateTo({
							url: payload.path
						});
					}
				});
			}
			console.log(payload);
		}
	}
};
</script>

<style lang="scss">
/* #ifndef APP-NVUE */
@import 'uview-ui/index.scss';
@import '/static/fonts/fonts.css';
@import '/style/goods.scss';
@import '/style/common.css';
@import '/style/compatible-safe-area.css';
@import '/style/animate.min.css';
@import '/style/completion-page.scss';
.flex-center-horizontal {
	display: flex;
	justify-content: center;
	align-items: center;
}
/* #endif */

/*每个页面公共css */
.button-none {
	background-color: rgba(255, 255, 255, 0);
	line-height: 1;
	border-radius: 0;
	padding: 0;
}
.cell-hover-class {
	opacity: 0.5;
}

.u-btn--main-theme {
	background-color: $theme-main-color !important;
	color: #fff;
}
@keyframes mineModifyAnimation {
	0% {
		top: calc((256rpx + 44rpx + var(--status-bar-height)) - 384rpx);
	}
	7% {
		top: calc((277rpx + 44rpx + var(--status-bar-height)) - 384rpx);
	}
	10% {
		top: calc((256rpx + 44rpx + var(--status-bar-height)) - 384rpx);
	}
}
</style>
